﻿using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using Simple.Repository.Models.Attendance;
using Simple.Repository.Models.ClassRoom;
using Simple.Services.System.FileInfo;
using Simple.Services.System.Recipes.Models;
using ZXing;
using static System.Net.Mime.MediaTypeNames;

namespace Simple.Services.System.ClassRoom
{
    public class InspectionRecordService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;
        private readonly FileInfoService _fileInfoService;
        private readonly ClassRoomService _classRoomService;

        public InspectionRecordService(SimpleDbContext context, ISimpleService services, FileInfoService fileInfoService, ClassRoomService classRoomService) : base(services)
        {
            _context = context;
            _fileInfoService = fileInfoService;
            _classRoomService = classRoomService;
        }

        public async Task<PageResultModel<InspectionRecordPageViewModel>> GetPageAsync(InspectionRecordQueryModel input)
        {
            var result = new PageResultModel<InspectionRecordPageViewModel>();
            var query = _context.Set<InspectionRecord>().Include(x => x.GardenHouseClassRoom).AsQueryable();

            // 根据条件查询
            if (input.GardenHouseClassRoomId.HasValue)
            {
                query = query.Where(p => p.GardenHouseClassRoomId == input.GardenHouseClassRoomId.Value);
            }
            else
            {
                var data = await _classRoomService.GetPageAsync(new ClassRoomPageInputModel() { PageNo = 1, PageSize = 1000 });
                query = query.Where(p => data.Rows.Select(x => x.Id).Distinct().ToList().Contains(p.GardenHouseClassRoomId));

            }
            if (input.StartTime.HasValue && input.EndTime.HasValue)
            {
                query = query.Where(p => input.StartTime > p.CreatedTime.Value && input.EndTime.Value < p.CreatedTime.Value.AddDays(1));

            }

            // 排序
            query = query.OrderByDescending(m => m.CreatedTime);




            var dataList = await query.ToListAsync();


            var userList = await _context.Set<SysUser>().ToListAsync();

            var dataViewModelList = MapperHelper.Map<List<InspectionRecordPageViewModel>>(dataList);

            foreach (var data in dataViewModelList)
            {
                if (data.ResponsiblePerson.HasValue)
                {
                    data.ResponsiblePersonStr = userList.FirstOrDefault(x => x.Id == data.ResponsiblePerson.Value).Name;
                }
                if (data.InspectionPerson.HasValue)
                {
                    data.InspectionPersonStr = userList.FirstOrDefault(x => x.Id == data.InspectionPerson.Value).Name;
                }
                data.RiskLevelStr = GetRiskLevelStr(data.RiskLevel);
            }

            var temp = new List<InspectionRecordPageViewModel>();

            var groupList = dataViewModelList.GroupBy(x => x.ClassRoomName).ToList();
            foreach (var item in groupList)
            {
                temp.Add(item.OrderByDescending(x => x.CreatedTime).FirstOrDefault());
            }


            // 获取总数量
            result.TotalRows = groupList.Count();
            // 分页查询
            //query = query.Page(input.PageNo, input.PageSize);
            result.Rows = temp.OrderByDescending(x => x.CreatedTime).Skip(input.PageNo - 1 * input.PageSize).Take(input.PageSize).ToList();
            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        public async Task<InspectionViewModel> GetDatailAsync(Guid inspectionId)
        {

            var dataInfo = await _context.Set<InspectionRecord>().Include(x => x.GardenHouseClassRoom).FirstOrDefaultAsync(c => c.Id == inspectionId);

            if (dataInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到巡检相关数据!");
            }

            var outResult = MapperHelper.Map<InspectionViewModel>(dataInfo);

            outResult.ResponsiblePersonStr = _context.Set<SysUser>().Where(x => x.Id == outResult.ResponsiblePerson.Value).FirstOrDefault().Name;
            outResult.InspectionPersonStr = _context.Set<SysUser>().Where(x => x.Id == outResult.InspectionPerson.Value).FirstOrDefault().Name;
            outResult.RiskLevelStr = GetRiskLevelStr(outResult.RiskLevel);

            if (!string.IsNullOrEmpty(dataInfo.Fields))
            {
                outResult.ImageList = await _fileInfoService.GetFilesByIdListAsync(dataInfo.Fields.Split(',').Select(x => Guid.Parse(x)).ToList());
            }
            return outResult;
        }

        public async Task<ResponsibleDto> GetRoomInfo(Guid gardenHouseClassRoomId)
        {
            var dataInfo = await _context.Set<GardenHouseClassRoom>().Where(x => x.Id == gardenHouseClassRoomId).FirstOrDefaultAsync();
            if (dataInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到教室相关数据!");
            }
            var result = new ResponsibleDto();
            if (dataInfo.ResponsiblePerson.HasValue)
            {
                var user = await _context.Set<SysUser>().Where(x => x.Id == dataInfo.ResponsiblePerson).FirstOrDefaultAsync();
                result.ResponsiblePerson = user?.Id;
                result.ResponsiblePersonStr = user?.Name;
            }
            result.ClassRoomName = dataInfo.CRoomName;
            result.GardenHouseClassRoomId = gardenHouseClassRoomId;

            return result;
        }

        public async Task<InspectionViewModel> GetLatestInspection(Guid gardenHouseClassRoomId)
        {

            var dataInfo = await _context.Set<InspectionRecord>().Include(x => x.GardenHouseClassRoom).Where(c => c.GardenHouseClassRoomId == gardenHouseClassRoomId).OrderByDescending(x => x.CreatedTime).FirstOrDefaultAsync();

            if (dataInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到巡检相关数据!");
            }

            var outResult = MapperHelper.Map<InspectionViewModel>(dataInfo);

            outResult.ResponsiblePersonStr = _context.Set<SysUser>().Where(x => x.Id == outResult.ResponsiblePerson.Value).FirstOrDefault().Name;
            outResult.InspectionPersonStr = _context.Set<SysUser>().Where(x => x.Id == outResult.InspectionPerson.Value).FirstOrDefault().Name;
            outResult.RiskLevelStr = GetRiskLevelStr(outResult.RiskLevel);
            if (!string.IsNullOrEmpty(dataInfo.Fields))
            {
                outResult.ImageList = await _fileInfoService.GetFilesByIdListAsync(dataInfo.Fields.Split(',').Select(x => Guid.Parse(x)).ToList());
            }

            return outResult;
        }


        public async Task<List<AppViewModel>> GetInspectionHistoryPage(Guid gardenHouseClassRoomId)
        {
            var result = new List<AppViewModel>();
            var dataList = await _context.Set<InspectionRecord>().Include(x => x.GardenHouseClassRoom).Where(c => c.GardenHouseClassRoomId == gardenHouseClassRoomId).OrderByDescending(x => x.CreatedTime).ToListAsync();

            foreach (var data in dataList)
            {
                var s = new AppViewModel();
                s.Id = data.Id;
                s.ClassRoomName = data.GardenHouseClassRoom.CRoomName;
                s.RiskLevelStr = GetRiskLevelStr(data.RiskLevel);
                s.CreatedTime = data.CreatedTime;
                result.Add(s);
            }
            return result;
        }



        public async Task<int> AddAsync(InspectionRecordAddDto model)
        {
            var position = new InspectionRecord();
            position.Id = Guid.NewGuid();
            position.GardenHouseClassRoomId = model.GardenHouseClassRoomId;
            position.ResponsiblePerson = model.ResponsiblePerson;
            position.RiskNumber = model.RiskNumber;
            position.RiskSourceName = model.RiskSourceName;
            position.RiskFactors = model.RiskFactors;
            position.RiskCategory = model.RiskCategory;
            position.RiskLevel = model.RiskLevel;
            position.PossibleAccidents = model.PossibleAccidents;
            position.ControlBasis = model.ControlBasis;
            position.InspectionPerson = _currentUser.UserId;

            var fields = new List<string>();
            if (model.FileIds != null && model.FileIds.Any())
            {
                position.Fields = string.Join(",", model.FileIds);
            }

            await _context.AddAsync(position);
            return await _context.SaveChangesAsync();
        }

        public async Task<int> EditAsync(InspectionRecordDto model)
        {
            if (!model.Id.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,巡检Id参数不能为Null!");
            }
            var data = await _context.Set<InspectionRecord>().Where(x => x.Id == model.Id.Value).FirstOrDefaultAsync();

            if (data == null)
            {
                throw AppResultException.Status404NotFound("未找到巡检相关数据，更新失败！");
            }
            var fields = new List<string>();
            //后台传文件表单
            if (model.ImageList != null && model.ImageList.Any())
            {
                foreach (var file in model.ImageList)
                {
                    var fileId = await _fileInfoService.UploadAsync(new FileInfo.Models.FileInfoInputModel { BusinessType = FileSource.ClassAlbums, File = file });
                    fields.Add(fileId.ToString());
                }
            }
            //小程序传文件Id
            if (model.FileIds != null && model.FileIds.Any())
            {
                fields = model.FileIds;
            }
            var fieldList = new List<string>();
            if (!string.IsNullOrEmpty(data.Fields))
            {
                fieldList = data.Fields.Split(',').Concat(fields).ToList();
            }
            else
            {
                fieldList = fieldList.Concat(fields).ToList();
            }
            if (model.RemoveImageIds != null && model.RemoveImageIds.Count > 0)
            {
                fieldList = fieldList.Except(model.RemoveImageIds).ToList();
            }


            data.RiskNumber = model.RiskNumber;
            data.RiskFactors = model.RiskFactors;
            data.RiskLevel = model.RiskLevel;
            data.PossibleAccidents = model.PossibleAccidents;
            data.Fields = string.Join(",", fieldList);
            data.ControlBasis = model.ControlBasis;
            data.RiskSourceName = model.RiskSourceName;
            data.RiskCategory = model.RiskCategory;
            _context.Update(data);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }
            return ret;
        }

        public async Task<int> DeleteAsync(IEnumerable<Guid> ids)
        {
            var positions = await _context.Set<InspectionRecord>()
                .Where(p => ids.Contains(p.Id))
                .ToListAsync();
            _context.RemoveRange(positions);
            return await _context.SaveChangesAsync();
        }

        private string GetRiskLevelStr(int riskLevel)
        {
            var str = string.Empty;
            switch (riskLevel)
            {
                case 1:
                    str = "低风险";
                    break;
                case 2:
                    str = "一般风险";
                    break;
                case 3:
                    str = "较大风险";
                    break;
                case 4:
                    str = "严重风险";
                    break;
            }
            return str;
        }
        private string GetFileSize(long size)
        {
            var num = 1024.00;
            if (size < num)
                return size + " B";
            if (size < Math.Pow(num, 2))
                return (size / num).ToString("f2") + " KB";
            if (size < Math.Pow(num, 3))
                return (size / Math.Pow(num, 2)).ToString("f2") + " MB";
            if (size < Math.Pow(num, 4))
                return (size / Math.Pow(num, 3)).ToString("f2") + " GB";
            return (size / Math.Pow(num, 4)).ToString("f2") + " TB";
        }



    }
}
